<?php

/**	
 *	social album object
 *	
 * 	the class is documented in the file itself. if you find any bugs help us out and report them. 
 * 	if you report a bug, make sure you give us enough information (include your code).
 *
 *	@author			pieter van peteghem <pieter@onedotonly.be>
 *
 *	@copyright		oneDot only <we@onedotonly.be>
 * 	@copyright		Copyright (c) 2010, oneDot only. All rights reserved.
 * 	@license		BSD License
 */


class SocialAlbum extends MOD {


	/**
	 *	constructor
	 *	
	 *	add module vars and reference (multiple modules on 1 page are possible)	
	 *	@param		array ($vars)
	 */
	 
	function __construct( $vars ) {
		$this->_addvars( $vars );
		$this->_ref();
	}


	/**
	 * 	define output
	 *
	 *	this is the album at the frontend
	 *	while rendering the form css is added, an IE check is executed, javascript is added
	 *
	 *	@return		string - the form
	 *	@param		string (action)
	 *	@param		boolean (vars->iewarn)
	 */
	 
	public function output() {
		
		if( $this->action )
			$result = $this->{ "filter_" . $this->action }();

		$this->addclass( $this->action );
		
		if( $result && is_array( $result ))
			$result = implode( "\n", $nodes );
			
		if( $result )
			return $this->parse( $result ) . $this->render_js();
	}
		 

	/**
	 *	filter social images
	 *	filter all social images that are connected with an object
	 */
	 
	 private function filter_album() {
	 	global $DB, $Object;
	 	
	 	if( $Object || $this->vars->ptype ) {
	 		
	 		// collect social streams connected to object
	 		$condt = (( $Object->id )? " parentid = " . $Object->id . " AND ": "" ) . (( $this->vars->personal )? " user = " . $_SESSION['uid'] . " AND ": "") ."active ORDER BY ID DESC" . (( $limit = $this->vars->limit)? " LIMIT " . $limit: "" );
	 		if ( $albums = $DB->reference( $this->vars->ptype, $condt, "social.album", false, 'social' )) {	 		
				foreach( $albums as $album ) {
				
					$album = array_shift( $DB->filter_objects( 'social.album', "ID = " . $album ));
					$res .= '<li>'; 
					
					
					if( !$DB->reference( 'social.album', (int) $album->id, 'social.img', false, 'social' )) {
						if( $album->get( 'source' ) == 'flickr' ) {
					
							$album_id = stripslashes( $album->get( 'id' ));
							if( substr( $album_id,0, 3 ) == 'www' || substr( $album_id, 0, 3 ) == 'htt' ) {
								$album_id = array_pop( explode( '/', (( substr( $album_id, 0, -1 ) != '/' )? substr( $album_id, 0, -1 ) : $album_id )));
							}
					
							$Flickr = new Flickr( engine_get( 'flickr.key' ));
							$photos = $Flickr->getAlbum( (int) $album_id, array( 'ownername', 'photo' ));
							if( !empty( $photos[ 'photo' ] )) {
								foreach( $photos['photo']['url'] as $picture ) {
									$new_image	= $DB->set( 'social.img', array( 'active' => 1, 'meta' => array( 'raw' => $picture, 'source' => 'flickr', 'id' => $album_id, 'llog' => date( 'Y-m-d H:i:s' ))));
									$DB->query( "insert into glue_social ( `parenttype`, `parentid`, `objtype`, `objid`, `rank`) values 
										(" . $DB->type( 'social.album' ) . ", " . (int) $album->id . ", " . $DB->type( 'social.img' ) . ", " . (int) $new_image . ", 5 )", 0 );
						
									$this->copy_thumb( $picture, ROOT . ACCOUNT . '/www/DB/social/', (int) $new_image );
								}
								$res .= '<ul>' . $this->render_list( $photos['photo']['url'], 'photo', 10, true, $this->vars->width ) . '</ul>';
							}
						}
						 /*else if( $album->get( 'source' ) == 'picasa' && $album->get( 'user' ) ) {
					
							$Picasa = new Picasa();
							//$photos = $Picasa->pictures( 'canatuur2007', '5149854089904202769', $this->vars->width );
							$photos = $Picasa->pictures( $album->get( 'user' ), (int) $album->get( 'id' ), $this->vars->width );
							$res .= '<ul>' . $this->render_list( $photos, 'photo', 10, true, $this->vars->width  ) . '</ul>';
						}*/
					} else {
						
						$imgs = array();
						$images = $DB->reference( 'social.album', (int) $album->id, 'social.img', false, 'social' );
						foreach( $images as $image ) {
							$thumb 	= '/public.img?id=' . $image . '&social=1&sze=' . $this->vars->width . '.0';
							$imgs[] = $thumb;
						}
						$res .= '<ul>' . $this->render_list( $imgs, 'photo', 10, true, $this->vars->width ) . '</ul>';
					}
					
					$res .= '</li>'; 
				}
			} else {
			
				$res .= '';
			}
	
			
	 	} else if( $vars->id && $vars->type ) {
	 		echo '<script type="text/javascript">console.log("bar")</script>';
	 	} else {
	 		echo '<script type="text/javascript">console.log("nothing")</script>';	
	 	}
	 	
	 	return $res;
	 	
	 }
	 
	function filter_target() {
		global $DB, $Object;
		
		if( $Object ) {
			
	 		$personal = false;
			if( $this->vars->personal || $_GET[ 'det' ] == 'me' )
				$personal = true;

			$results = $DB->reference( $Object->type, 'parentid = ' . (int) $Object->get( 'ID' ) . (( $personal )? ' && user = ' . $_SESSION['uid'] : '' ), 'social.album', null, 'social' );
			
			if( $results && ( $objects = $DB->filter_objects( 'social.album', "ID in(" . implode( ",", $results ) . ") && active order by rank desc limit 240" ))) {
				foreach( $objects as $Album ) {
					
					if( !$DB->reference( 'social.album', (int) $Album->id, 'social.img', false, 'social' )) {
				
						if( $Album->get( 'source' ) == 'flickr' ) {
						
							$album_id = stripslashes( $Album->get( 'id' ));
							if( substr( $album_id,0, 3 ) == 'www' || substr( $album_id, 0, 3 ) == 'htt' ) {
								$album_id = array_pop( explode( '/', (( substr( $album_id, 0, -1 ) != '/' )? substr( $album_id, 0, -1 ) : $album_id )));
							}
						
							$Flickr = new Flickr( engine_get( 'flickr.key' ));
							$photos = $Flickr->getAlbum( (int) $album_id, array( 'ownername', 'photo' ));
							
							if( !empty( $photos[ 'photo' ] )) {
								foreach( $photos['photo']['url'] as $picture ) {
									$new_image	= $DB->set( 'social.img', array( 'active' => 1, 'creator' => $_SESSION['uid'], 'meta' => array( 'raw' => $picture, 'source' => 'flickr', 'id' => $album_id, 'llog' => date( 'Y-m-d H:i:s' ))));
									$DB->query( "insert into glue_social ( `parenttype`, `parentid`, `objtype`, `objid`, `rank`, `user` ) values 
										(" . $DB->type( 'social.album' ) . ", " . (int) $Album->id . ", " . $DB->type( 'social.img' ) . ", " . (int) $new_image . ", 5, " . $_SESSION['uid'] . " )", 0 );
						
									$this->copy_thumb( $picture, ROOT . ACCOUNT . '/www/DB/social/', (int) $new_image );
								}
							}
						}
						else if( stristr( $Album->get( 'source' ), 'facebook' )) {
						
							// include gigya
							include_once( ENGINE_CORE . '/modules/social.gigya/GSSDK.php' );
							$gigya	= json_decode( engine_get( 'gigya.connect' ));
							
							$request	= new GSRequest( $gigya->key, $gigya->secret, "getPhotos" );
							
							$request->setParam( 'albumIDs' , $Album->get( 'source' ));
							$request->setParam( 'uid' , $_SESSION[ 'gigyauid' ] );
							
							$response	= $request->send();
							if( $response->getErrorCode() == 0 ) {
								$photos = $response->getArray( 'photos' );
								foreach( $photos as $photo ) {
									$picture = $photo->getString( 'photoURL' );
									$new_image	= $DB->set( 'social.img', array( 'active' => 1, 'creator' => $_SESSION['uid'], 'meta' => array( 'raw' => $picture, 'source' => 'facebook', 'id' => $Album->get( 'source' ), 'llog' => date( 'Y-m-d H:i:s' ))));
									$DB->query( "insert into glue_social ( `parenttype`, `parentid`, `objtype`, `objid`, `rank`, `user`) values 
										(" . $DB->type( 'social.album' ) . ", " . (int) $Album->id . ", " . $DB->type( 'social.img' ) . ", " . (int) $new_image . ", 5, " . $_SESSION['uid'] . " )", 0 );
						
									$this->copy_thumb( $picture, ROOT . ACCOUNT . '/www/DB/social/', (int) $new_image );
								}
							}
						}
					}								
				}
				
				$images = $DB->reference( 'social.album', array_pop( $results ), 'social.img', false, 'social' );
				$thumb 	= '/public.img?id=' . array_pop( $images ) . '&social=1&sze=' . $this->vars->size;
			
				$nodes = "<img class='cont' src='" . $thumb . "' alt='". engine_get( "title" ) . "' />";
				
			} else {
				$this->addclass( 'empty' );
				$nodes = "&nbsp;";
			}
		}
		
		$this->set_attribute( "id", $this->vars->anchor );
				
		return $nodes;
	}
	  
	
#	Action nav slide
	private function filter_nav() {
		
		$this->addclass( $this->vars->navtype );
		
		if( $nav = $this->vars->navtype )
			$nodes = $this->{ "render_" . $nav }( $nav );
				
		return $nodes;
	}
	

	/**
	 * copy to own server
	 * @param	string	original source
	 * @param	string	destination
	 * @param	string	name
	 * @param	string 	extension
	 */

	private function copy_thumb( $source, $dest, $name, $extension = '.jpg' ) {
	
		$image 		= @file_get_contents( $source );
		$new_img 	= fopen ( $dest . $name . $extension, 'w');
		fwrite ( $new_img, $image );
		fclose ( $new_img ); 
		
		return $new_img;
	}
	  
	  
	/**
	 * 	check if url exists
	 *	@param		string
	 *	@return		int
	 */
	function url_exists( $url ) {
		@ $headers = get_headers($url);
    	return preg_match('/^HTTP\/\d\.\d\s+(200|301|302)/', $headers[0]);
	}  


	/**
	 * render any type of list defined by an array 
	 * @param	string		classname
	 * @param	int			limit
	 * @param	boolean		image?!
	 * @param	width		define image width
	 * @return	text		html list
	 */

	function render_list( $nodes, $class = 'list_item', $limit = false, $img = false, $width = false ) {
	
		$i = 0;
		if( $nodes ) {
		foreach ($nodes as $node) {
			if ( $img )
				$res .= '<li class="' . $class .'"><img ' . (( $width ) ? 'style="width:' . $width . 'px;"' : '' ) . ' src="' . $node . '"/></li>';
			else 
				$res .= '<li class="' . $class .'">' . $node . '</li>';
				
			$i++;
			if ( $limit && $i == (int) $limit ) break;
		}
		
		return $res;
		}
	} 
#	Render NAV.hover
	private function render_hover( $class ) {
		global $DB, $Album;
		
				
		if( $Album && !$this->vars->override_album ) {
			$Album->set_cache( "media", $group = $Album->media->reference( $Album->objtype ));
			$Album->set_cache( "album", $this->vars );
			$this->js = "mod = new MediaAlbum( 'target', ". $Album->json( "ID", "album", "media" ) ." );";
		
		} else if( $this->vars->objects ) {
			if( $objects = $DB->filter_objects( $this->vars->type ))
				foreach( $objects as $Obj )
					if( $id = $Obj->media->get( $this->vars->objtype )->ID )
						$group[] = array( "name"=>$Obj->get( "name" ), "id"=> $id, "uri"=> $Obj->uri());
			
			$this->js = "mod = new MediaAlbum( 'target', " . json_encode( array( "album"=> $this->vars, "media"=> $group )) ." );";
			$link = "<span class='link'></span>";
		}
		
		if( count( $group ) > 1 )
			$nav = "<span class='nav $class linked'><span class='left'></span>$link<span class='right'></span><span class='info'></span></span>";
		
		return $nav;
	}
	
#	Render NAV.classic
	private function render_classic( $class ) {
		global $DB, $Album;
		
		if( !$group = $Album->media->reference( $Album->objtype )) $group = array();
		
		if( $this->vars->collect )
			foreach( $this->vars->collect as $part )
				if( $add = $Album->{ $part }->media->reference( $Album->objtype ))
					$group = array_merge( $group, $add );		
		
		
		$Album->set_cache( "media", $group );
		$Album->set_cache( "album", $this->vars );
		
		$this->js = "mod = new MediaAlbum( 'target', ". $Album->json( "ID", "album", "media" ) ." );";
		
		if( count( $group ) > 1 )
			$nav = "<span class='nav $class'><span class='left'></span><span class='right'></span><span class='info'></span></span>";
		
		return $nav;
	}

#	Render NAV.slide
	private function render_slide( $nav ) {
		global $DB, $Album;
		
		if( !$Album ) return false;
		
		$Album->set_cache( "album", $this->vars );
		
		$nodes[] = "<span class='reel'><span class='in'></span></span>";
		$nodes[] = "<span class='left'></span><span class='info'></span><span class='right'></span>";
		
		$this->js = "mod = new MediaAlbum( '$nav', ". $Album->json( "ID", "album", "name" ) ." );";
		
		return $nodes;
	}
	
#	Render NAV.snake
	private function render_snake( $nav ) {
		global $DB, $Album;
		
		$Album->set_cache( "album", $this->vars );
		
		$nodes[] = "<span class='left'></span><span class='reel'><span class='in'></span></span>";
		$nodes[] = "<span class='right'></span>";
		
		$this->js = "mod = new MediaAlbum( '$nav', ". $Album->json( "ID", "album", "name" ) ." );";
		
		return $nodes;
	}

#	Render NAV.thumbs
	private function render_thumbs( $nav ) {
		global $DB, $Object;
		
		if( $Object ) {
	 		$personal = false;
			if( $this->vars->personal || $_GET[ 'det' ] == 'me' )
				$personal = true;

			if( $albums = $DB->reference( $Object->type,'parentid = ' . (int) $Object->get( 'ID' ) . (( $personal )? ' && user = ' . $_SESSION['uid'] : '' ), 'social.album', null, 'social' )) {
				$img = array();
				$imgs = array();
				foreach( $albums as $album ) {
				
					if( $images = $DB->reference( 'social.album', (int) $album, 'social.img', false, 'social' )) {
						foreach( $images as $image ) {
							$img[] = $image;
						}				
					}
				}
			}
			
			
			if( $picies = $DB->reference( $Object->type,'parentid = ' . (int) $Object->get( 'ID' ) . (( $personal )? ' && user = ' . $_SESSION['uid'] : '' ), 'social.img', null, 'social' )) {
			
				foreach( $picies as $pic ) {
					$img[] = $pic;
				}
			}
			
			if( $img ) {
				//array_reverse( $img );
				$i = 0;
				foreach( $img as $pic ) {
					$imgs[] = $pic;
					$i++;			
					if( $this->vars->limit && $i >= $this->vars->limit )
						break;
				}
			
				$alb = array( 'size' => '410.0', 'tsize' => '49.36', 'anchor' => $this->vars->anchor, 'navtype' => 'hover', 'objtype' => 'social.img', 'title' => engine_get( 'title' ));
			
				$nodes = "<span class='nav'></span>";
				$this->js = "mod = new SocialAlbum( '$nav', ". json_encode( array( 'media' => $imgs, 'album' => $alb )) . " );";
			}
		}
		/*$Album->set_cache( "album", $this->vars );
		
		$nodes[] = "<span class='nav'></span>";
		
		$this->js = "mod = new MediaAlbum( '$nav', ". $Album->json( "ID", "album", "name" ) ." );";*/
		
		return $nodes;
	}
	
#	Render thumb (basic)
	private function render_thumb( $el, $url = false, $raw = false ) {
		global $Album, $DB;

		$descr = ( $el->get( 'nameid' ))? $el->get( 'name' ): $el->get( 'raw' );
			
		$url = ( $url )? "<a href='$url{$el->id}'>" :(( $raw )? "<a href='/DB/media/{$el->id}.jpg' target='_blank'>": "" );
		
		return "<span class='img'>$url<img src='/public.img?sze={$this->vars->imgsize}&id={$el->id}' />$descr" . (( $url )? "</a>": "" ) . "</span>";
	}


}


/** 
 * FLICKR CLASS
 *
 * This can be used to communicate with flickr api
 * This is only the beginning of a flickr communication.. should be expanded in the future!
 *
 * @author		Pieter Van Peteghem <pieter@onedotonly.be>
 * @version		version 0.01 beta
 *
 * @copyright	oneDot only <we@onedotonly.be> Copyright (c) 2010, oneDot only. All rights reserved.
 * @license		BSD License
 */

class Flickr {

	CONST FLICKR_URL 	= 'http://api.flickr.com/services/rest/';

	
	/**
	 * Default constructor
	 *
	 * @return	void
	 * @param	string $apikey			The consumer key to use.
	 */
	 
	public function __construct( $apikey ) {
		$this->apikey = $apikey;
	}
	
	
	/**
	 * get album with info
	 *
	 * @return	array 
	 * @param 	user
	 * @param 	albumid
	 */

	public function getAlbum( $album, $what ) {
		
		// define url with api key & album
		$url = self::FLICKR_URL . '?method=flickr.photosets.getPhotos&api_key=' . $this->apikey . '&photoset_id=' . $album . '&extras=url_o,url_t&format=json&nojsoncallback=1';
		
		// get album info
		$album 	= json_decode( file_get_contents( $url ));
		$album	= $album->photoset;
		
		if ( is_array( $what )) {
			foreach ( $what as $info ) {
				if ( $info != 'photo') {
					$result[$info] = $album->$info;
				} else { 
					$result[$info] = $this->pictures( $album->$info );
				}
			}
		} else {
			if ( $info != 'photo') {
				$result[$info] = $album->$info;
			} else { 
				$result[$info] = $this->pictures( $album->$info);
			}
		}
		
		return $result;
		
	}	
	
	
	/**
	 * render pictures 
	 *
	 * @return 	list 
	 * @param 	list 	$nodes
	 */
	 
#'http://farm' + item.farm + '.static.flickr.com/' + item.server + '/' + item.id + '_' + item.secret + '_m.jpg'
	public function pictures( $nodes, $size = 'b' ) {
	
		$i = 0;
		if( $nodes ) {
		foreach ($nodes as $node) {
			
			$result[ 'url' ][$i]	= 'http://farm' . $node->farm . '.static.flickr.com/' . $node->server . '/' . $node->id . '_' . $node->secret . '_' . $size . '.jpg';
			$result[ 'title' ][$i] = $node->title;
			
			$i++;
		}
		
		return $result;
		}
	
	}
	
	
	/**
	 * 	check if url exists
	 *	@param		string
	 *	@return		int
	 */
	function url_exists( $url ) {
		@ $headers = get_headers($url);
    	return preg_match('/^HTTP\/\d\.\d\s+(200|301|302)/', $headers[0]);
	}  
	

}
 
 
/** 
 * PICASA CLASS
 *
 * This can be used to communicate with picasa api
 * This is only the beginning of a picasa communication.. should be expanded in the future!
 *
 * @author		Pieter Van Peteghem <pieter@onedotonly.be>
 * @version		version 0.01 beta
 *
 * @copyright	oneDot only <we@onedotonly.be> Copyright (c) 2010, oneDot only. All rights reserved.
 * @license		BSD License
 */



class Picasa {

	CONST PICASA_URL 	= 'http://picasaweb.google.com/data/feed/base';

	
	/**
	 * Default constructor
	 *
	 * @return	void
	 * @param	string $apikey			The consumer key to use.
	 * @param	string $apisecret 		The consumer secret to use.
	 
	 
	 public function __construct($apikey, $apisecret) {
		$this->apikey = $apikey;
		$this->apisecret = $apisecret;
	}*/
	
	
	/**
	 * get album with info
	 *
	 * @return	array 
	 * @param 	user
	 * @param 	albumid
	 */
	 
	public function getAlbum( $user, $album ) {
		
		if( $this->url_exists( self::PICASA_URL .  '/user/' . $user . '/albumid/' . $album . '?alt=rss&kind=photo&hl=en_US' )) {
			$xml 	= self::PICASA_URL .  '/user/' . $user . '/albumid/' . $album . '?alt=rss&kind=photo&hl=en_US';
			$list 	= simplexml_load_file($xml);
			foreach ($list->channel->item as $item) {
				$photos[] = $item;
			}	
			return $photos;
		}
	} 
	
	
	/**
	 * render pictures 
	 *
	 * @return 	list 
	 * @param 	user 
	 * @param 	album
	 * @param 	width
	 */
	 
	public function pictures( $user, $album, $width = 250 ) {
	
		$items = (array) $this->getAlbum( $user, $album );
		foreach ($items as $item ) {
			$url = $item->enclosure->attributes()->url;
			$url = $this->getPicture( $url, $width );
			$photos[] = $url;
		}
		
		return $photos;
		
	}



	/**
	 * Get pictures url and resize
	 * 
	 * @return		string
	 * @param		string $url		given url
	 * @param		int $resize		given width/height
	 */
	
	function getPicture ( $url, $resize = 250 ) {
	
		if ( $url )
			$img = explode( '/', $url);
			$img[count($img) - 1] = 's' . $resize . '/' . $img[count($img) - 1];
			$url = implode('/', $img);
	
		return $url;			

	}

	
	
	/**
	 * 	check if url exists
	 *
	 *	@param		string
	 *	@return		int
	 */
	function url_exists($url) {
		@ $headers = get_headers($url);
    	return preg_match('/^HTTP\/\d\.\d\s+(200|301|302)/', $headers[0]);
	}  
		

}